import React, { useCallback, useEffect, useRef } from "react";
import * as echarts from "echarts";

interface EChartsHookOptions {
  options: echarts.EChartsOption;
}

type EChartsHookReturnValue = [
  React.RefObject<HTMLDivElement>,
  echarts.ECharts | null,
];

export function useECharts({
    options,
}: EChartsHookOptions): EChartsHookReturnValue {
    const chartRef = useRef<HTMLDivElement>(null);
    const chartInstanceRef = useRef<echarts.ECharts | null>(null);

    const initECharts = useCallback(() => {
        if (chartRef.current) {
            const instance = echarts.init(chartRef.current);
            instance.setOption(options);
            return instance;
        }
        return null;
    }, [options]);

    useEffect(() => {
        chartInstanceRef.current = initECharts();
        window.addEventListener("resize", () => {
      chartInstanceRef.current!.resize();
        });
        return () => {
            if (chartInstanceRef.current) {
                chartInstanceRef.current.dispose();
            }
        };
    }, [initECharts]);

    return [chartRef, chartInstanceRef.current];
}
